<template>
  <div class="app-container">

    <!--搜索表单-->
    <el-form :inline="true" :model="searchstudent" class="demo-form-inline">
      <el-form-item label="姓名">
        <el-input
          v-model="searchstudent.name"
          placeholder="请输入学生姓名"
        />
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="searchstudent.gender" placeholder="请选择">
          <el-option label="男" value="0"></el-option>
          <el-option label="女" value="1"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="出生时间">
        <el-date-picker
          v-model="entrydate"
          clearable
          value-format="yyyy-MM-dd"
          type="daterange"
          placeholder="选择日期"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 400px; margin-left: 20px"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
         <el-button type="info" @click="clear">清空</el-button>
      </el-form-item>
    </el-form>



    <!--按钮-->
    <el-row>
      <el-button type="danger" size="medium" @click="deleteBatch">- 批量删除</el-button>
      <el-button type="primary" size="medium" @click="dialogVisible = true; student = { image: ''};" >+ 新增学生</el-button>
    </el-row>

    <!--添加数据对话框表单-->
    <el-dialog ref="form" title="编辑学生" :visible.sync="dialogVisible" width="30%">
      <el-form ref="form" :model="student" label-width="80px" size="mini">
        <!-- <el-form-item label="用户名">
          <el-input v-model="student.id"></el-input>
        </el-form-item> -->
        <el-form-item label="学生姓名">
          <el-input v-model="student.name"></el-input>
        </el-form-item>

        <el-form-item label="性别" >
          <el-select v-model="student.gender" placeholder="请选择" style="width:100%" >
             <el-option
              v-for="item in genderList"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleFileChange"
            :before-upload="beforeAvatarUpload"
            accept="image/*"
          >
            <img v-if="previewImage || student.image" :src="previewImage || student.image" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="班级">
          <el-select v-model="student.classId" placeholder="请选择" value-key="student.classId" style="width:100%">
            <el-option
              v-for="item in classdata"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="出生日期">
          <el-date-picker
            v-model="student.birthDate"
            clearable
            type="date"
            placeholder="选择日期"
            size="small"
            style="width:100%"
          ></el-date-picker>
        </el-form-item>


        <el-form-item>
          <el-button type="primary" @click="add()">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <br>
    <!--表格-->
    <template>
      <el-table :data="tableData" style="width: 100%" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"  align="center"></el-table-column>
        <el-table-column  prop="name"  label="姓名"  align="center"></el-table-column>
        <el-table-column prop="image" label="头像" align="center">
          <template slot-scope="scope">
            <el-image style="width: auto; height: 40px; border: none; cursor: pointer" :src="scope.row.url"></el-image>
          </template>
        </el-table-column>

        <el-table-column align="center" label="性别">
          <template slot-scope="scope">
            <span style="margin-right: 10px">
            {{scope.row.gender == "1" ? "男" : "女"}}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="班级">
          <template slot-scope="scope">
            <span style="margin-right: 10px">{{scope.row.className}}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="出生时间">
          <template slot-scope="scope">
            {{scope.row.birthDate ? scope.row.birthDate.replace('T',' '):''}}
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="update(scope.row.id)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteById(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!--分页工具条-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :background="background"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="5"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount">
    </el-pagination>
  </div>
</template>

<script>
import { page, add, update, deleteById, selectById,deleteBatch } from "@/api/student.js";

import {
  findAll as class_findAll

} from "@/api/class.js";
// import { findAll } from "@/api/dept.js";
import { getToken } from '@/utils/auth';
import request from '@/utils/request';

export default {
  data() {
    return {
      background: true,
      // 每页显示的条数
      pageSize: 5,
      // 总记录数
      totalCount: 100,
      // 当前页码
      currentPage: 1,
      // 添加数据对话框是否展示的标记
      dialogVisible: false,
      // 班级模型数据
      classdata: [],
      // 学生模型数据
      searchstudent: {
        name: "",
        gender: "",
      },
      student: {},
      deptList: [],
      genderList: [{id: 1,name: "男"},{id: 2,name: "女"}],
      classdata: [],
      previewImage: '', // 预览图片URL
      selectedFile: null, // 选中的文件对象
      // jobList: [
      //   {
      //     id: 1,
      //     name: "班主任",
      //   },
      //   {
      //     id: 2,
      //     name: "讲师",
      //   },
      //   {
      //     id: 3,
      //     name: "学工主管",
      //   },
      //   {
      //     id: 4,
      //     name: "教研主管",
      //   }
      // ],

      beginTime: "",
      endTime: "",
      entrydate: "",

      // 被选中的id数组
      selectedIds: [],
      // 复选框选中数据集合
      multipleSelection: [],
      // 表格数据
      tableData: [],
      token: {token: getToken()}
    };
  },

  mounted() {
    this.class_findAll() // 获取班级信息
    this.page(); //当页面加载完成后，发送异步请求，获取数据

    // findAll().then((result) => {
    //   this.deptList = result.data.data;
    // });
  },

  methods: {
    // 获取班级信息
    class_findAll(){
      class_findAll().then((result) => {
        this.classdata = result.data.data.map(item => ({
          id: item.id,
          name: item.name,
          gradeName: item.grade.name
        }))
        console.log(this.classdata)
        // console.log("classdata",this.classdata)
      });
      
    },
    // 查询分页数据
    page() {
      const data = {
        keywords: this.searchstudent.name,
        gender: this.searchstudent.gender,
        classId: this.classId,
        beginTime: this.beginTime,
        endTime: this.endTime,
        pageSize: this.pageSize,
        pageNum: this.currentPage,
      }
      page(data).then((res) => {
        this.totalCount = res.data.data.total;
        this.tableData = res.data.data.records;
      });
    },

    // 复选框选中后执行的方法
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    // 查询方法
    onSubmit() {
      this.currentPage = 1;
      this.page();
    },

    // 清空搜索条件
    clear(){
      this.searchstudent = { name: "", gender: "" };
      this.beginTime = "";
      this.endTime = "";
      this.entrydate = "";
      this.currentPage = 1;
      this.page();
    },
    // 添加/更新数据
    async add() {
      try {
        // 如果有选择的文件，先上传图片
        if (this.selectedFile) {
          try {
            await this.uploadImage();
          } catch (error) {
            console.error('图片上传失败:', error);
            // 图片上传失败不阻止数据保存，继续执行
          }
        }
        
        const apiCall = this.student.id ? update(this.student) : add(this.student);
        const successMessage = this.student.id ? "恭喜你，更新成功" : "恭喜你，保存成功";
        
        apiCall.then((resp) => {
          if (resp.data.code === 200) {
            this.page();
            this.$message.success(successMessage);
            this.resetForm();
          } else {
            this.$message.error(resp.data.msg || "操作失败");
          }
        }).catch((error) => {
          console.error('保存失败:', error);
          this.$message.error('保存失败，请重试');
        });
      } catch (error) {
        console.error('操作失败:', error);
        this.$message.error('操作失败，请重试');
      }
    },
    
    // 重置表单
    resetForm() {
      this.student = {};
      this.previewImage = '';
      this.selectedFile = null;
      this.dialogVisible = false;
    },
    // 编辑学生信息
    update(id) {
      // 打开窗口
      this.dialogVisible = true;
      // 清空预览状态
      this.previewImage = '';
      this.selectedFile = null;
      // 发送请求获取学生信息
      selectById(id).then((result) => {
        if (result.data.code === 200) {
          this.student = result.data.data;
        } else {
          this.$message.error(result.data.msg || "获取学生信息失败");
        }
      }).catch((error) => {
        console.error('获取学生信息失败:', error);
        this.$message.error("获取学生信息失败，请重试");
      });
    },


    //分页
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.pageSize = val;
      this.page();
    },

    handleCurrentChange(val) {
      // 重新设置当前页码
      this.currentPage = val;
      this.page();
    },


    //删除学生信息
    deleteById(id){
      this.$confirm("此操作将删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
          //发送AJAX请求
          const data = new FormData();
          data.append("id", id);
          deleteById(data).then((resp) => {
            if (resp.data.code === 200) {
              //删除成功
              this.$message.success("恭喜你，删除成功");
              this.page();
            } else {
              this.$message.error(resp.data.msg || "删除失败");
            }
          }).catch((error) => {
            console.error('删除失败:', error);
            this.$message.error("删除失败，请重试");
          });
      }).catch(() => {
          //用户点击取消按钮
          this.$message.info("已取消删除");
        });
    },


    // 批量删除学生信息
    deleteBatch() {
      // 检查是否选择了数据
      if (this.multipleSelection.length === 0) {
        this.$message.warning("请先选择要删除的数据");
        return;
      }
      
      // 弹出确认提示框
      this.$confirm("此操作将删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
          //用户点击确认按钮
          //1. 创建id数组, 从 this.multipleSelection 获取即可
          this.selectedIds = this.multipleSelection.map(item => item.id);
          
          //2. 发送AJAX请求
          deleteBatch(this.selectedIds).then((resp) => {
            if (resp.data.code === "200" || resp.data.code === 200) {
              //删除成功
              this.$message.success("恭喜你，删除成功");
              // 清空选中状态
              this.multipleSelection = [];
              this.selectedIds = [];
              // 刷新数据
              this.page();
            } else {
              this.$message.error(resp.data.msg || "删除失败");
            }
          }).catch((error) => {
            console.error('删除失败:', error);
            this.$message.error("删除失败，请重试");
          });
      }).catch(() => {
          //用户点击取消按钮
          this.$message.info("已取消删除");
        });
    },


    //文件选择处理
    handleFileChange(file, fileList) {
      if (file.raw) {
        // 验证文件
        if (this.beforeAvatarUpload(file.raw)) {
          this.selectedFile = file.raw;
          // 创建预览URL
          const reader = new FileReader();
          reader.onload = (e) => {
            this.previewImage = e.target.result;
          };
          reader.readAsDataURL(file.raw);
        }
      }
    },
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isImage) {
        this.$message.error("只能上传图片文件!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isImage && isLt2M;
    },
    
    // 上传图片到服务器
    async uploadImage() {
      if (!this.selectedFile) {
        return null;
      }
      
      const formData = new FormData();
      formData.append('file', this.selectedFile);
      formData.append('id', this.student.id);
      
      try {
        const response = await request({
          url: '/student/updateUrl',
          method: 'put',
          data: formData,
          headers: {
            'Content-Type': 'multipart/form-data',
            // ...this.token
            'Authorization': `Bearer ${this.token}`
          }
        });
        return response.data;
      } catch (error) {
        this.$message.error('图片上传失败');
        throw error;
      }
    },
  },


  watch: {
    entrydate(val) {
      if (val && val.length >= 2) {
        this.beginTime = val[0];
        this.endTime = val[1];
      } else {
        this.beginTime = "";
        this.endTime = "";
      }
    },
  },
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
